import { useEffect, useCallback } from "react";
import { homeDir, desktopDir, documentDir, downloadDir } from "@tauri-apps/api/path"; 
import { invoke } from "@tauri-apps/api/core";
import { Link } from "react-router-dom";
import { ExplorerFunctions } from "./FileExplorerFunctions.tsx"
import { getCurrentWindow } from "@tauri-apps/api/window";
import { LogicalSize } from '@tauri-apps/api/dpi';
import { Timer, Clock } from "./Timer.tsx";
import { UserInterface, OSSAccess } from "./UserInterface.tsx";
import "./FileExplore.css";

function FileExplorer() { 
  const { 
    routeinforef,
    location,
    files,
    error,
    isLoading, setIsLoading,
    selectedFiles, setSelectedFiles,
    currentPath, setCurrentPath,
    logInStatus, setLogInStatus, 
    isUploading,
    uploadStatus, 
    uploadToOSS,
    handleCheckboxChange,
    handleRowClick,
    handleRowDoubleClick, 
    handleDeleteAccount,
    handleDeleteFiles,
    navigateUp,
    handleSelectFolder,
    formatFileSize, 
    navigateToSpecialDir,
    loadDirectory,
  } = ExplorerFunctions();
  const { 
    ossAccess, setOssAccess,
  } = UserInterface();

  // 当路径变化时加载目录内容
  useEffect(() => { 
    const loadDic = async () => {
      setIsLoading(true);  
      if(currentPath){
        loadDirectory(currentPath);
        console.log("current path is ", currentPath);
      }else{ 
        const locationState = location.state.path;
        if(locationState){
          setCurrentPath(locationState);
          loadDirectory(locationState);
        }
      }
      setSelectedFiles(new Set());
      setIsLoading(false);
    };
    loadDic();
  }, [currentPath, location.state.path]);  

  const checkOssAccess = useCallback(
    async () => {
      const route_info = {
        user : location.state.routeInfo.user,
        url : location.state.routeInfo.url,
      }
      routeinforef.current = route_info;
      setOssAccess(location.state.oss);
      if(!location.state.oss){
        // console.log("files list user", routeinforef.current.user);
        setIsLoading(true);
        if(route_info.user && route_info.url){
          try {
            const ossAccess = await invoke<OSSAccess>("get_oss_accesskey", {
              user : route_info.user,
              mongodbUrl : route_info.url
            });
            setOssAccess(ossAccess);
            console.log("OSS Access key ID", ossAccess.oss_access_id);
          } catch (error) {
            console.error("Failed to get user:", error);
          }
        }else{
          console.error("User and URL is not defined");
        }
        setIsLoading(false);
      }else{
        console.log("OSS Access key ID already exists.");
      }
    }, [ossAccess, routeinforef]
  )

  useEffect(()=> {
    const handleStorageChange = ()=> {
      const logInResponse = sessionStorage.getItem("login-response");
      setLogInStatus(logInResponse || "");
    }
    window.addEventListener('storage', handleStorageChange);
    // 监听事件
    handleStorageChange();
    return () => {
        window.removeEventListener('storage', handleStorageChange);
    };
  }, [sessionStorage]);

  useEffect(() => {
    checkOssAccess();
    getCurrentWindow().setSize(new LogicalSize(1600, 600));
  }, []);

  return (
    <div className="filExplorer">
      <div className="files-topbar">
        <input id="current-path" 
              type="text" 
              placeholder="Invalid path"
              onChange={(e)=>setCurrentPath(e.currentTarget.value)}
              value={currentPath} />
        <div className="account"> 
          <div id="message-bar">
            <Clock />
            <h1 id="file-explorer">File Explorer</h1>
            {isLoading && (
              <div id="loading-bar">
                <span id="toploading">🔄loading...</span>
                <Timer />
              </div>
            )}
          </div> 
          <div className="toolsbar">  
            <div className="quick-access">
              <button onClick={navigateUp}>⬆️Up</button>
              <button onClick={() => navigateToSpecialDir(homeDir)}>🏠Home</button>
              <button onClick={() => navigateToSpecialDir(desktopDir)}>🖥️Desktop</button>
              <button onClick={() => navigateToSpecialDir(documentDir)}>📁Documents</button>
              <button onClick={() => navigateToSpecialDir(downloadDir)}>⬇️Downloads</button>
              <button onClick={handleSelectFolder}>🔍Browse</button>
            </div>  
     
            <div className="buttons-container-file">
              <div className="cloud-file">
                <button id="upload" onClick={uploadToOSS} 
                  disabled={
                    isUploading || !ossAccess || !logInStatus
                }>
                  {isUploading ? '⏳Uploading...' : '⬆️Upload'}
                </button>
                <Link to="/cloud-files-list" 
                  state ={{ 
                    path : currentPath,
                    routeInfo : routeinforef.current,
                    oss: ossAccess
                   }}>
                  <button id="cloud-list" 
                    disabled={!logInStatus || !ossAccess}
                  >
                    ☁️Cloud Files List 
                  </button>
                </Link>
              </div>
              <div className="local-file">
                <Link to="/editor" state={{ 
                  path : currentPath,
                  routeInfo : routeinforef.current,
                  oss: ossAccess
                }}>
                  <button id="add-local-file" disabled={!currentPath}>➕Add</button>
                </Link>
                <button id="delete-local-file" 
                        onClick={handleDeleteFiles} 
                        disabled={selectedFiles.size === 0}>
                  🗑️Delete
                </button>
              </div>
            </div>
          </div> 

          <div id="account-buttons">
            <Link to="/">  
            {/* 如果没有登陆成功就无法登出 */}
              <button id="files-logout" disabled={!logInStatus}>🚪Log Out</button>
            </Link>
            <Link to="/change-password" state={{ 
                  path : currentPath,
                  routeInfo : routeinforef.current
                }}>
                  {/* 如果没有登陆成功就无法修改密码 */}
              <button id="files-changepassword" disabled={!logInStatus}>⚙️Change Password</button>
            </Link>
            <button id="delete-account" onClick={handleDeleteAccount}>
              ⚠️Delete Account
            </button>  
          </div>
        </div>
        <div className="fliestatusbar">
          {uploadStatus ? (
            ((uploadStatus.includes('Uploading') ? (
              <div id="isuploadingbar">
                <div id="uploading">🔄{uploadStatus}</div>
                <Timer/>
              </div>
            ) : ( 
              <div className={uploadStatus.includes('Failed') ?
              'upload-status error' : 'upload-status success'}>
                {uploadStatus}
              </div>
            )
            ))
          ) : (logInStatus ? (<div id="login-status">{logInStatus}</div>
            ) : (
            <div id="loggingin-status-bar">
              <div id="loggingin">🔄Logging in...</div>
              <Timer/>
            </div>
          ))}
          
            {/* 显示选中的文件数量和操作按钮 */}
          {selectedFiles.size > 0 && (
            <div className="files-selected-info">
              Selected {selectedFiles.size} file(s)
            </div>
          )}
        </div>
        <table id="tabletoptop">
          <colgroup>
            <col className="checkbox" />
            <col className="name" />
            <col className="type" />
            <col className="size" />
          </colgroup>
          <thead id="tabletop">
            <tr>
              <th className="checkbox">😺Select</th>
              <th className="name">😸Name</th>
              <th className="type">😹Type</th>
              <th className="size">😻Size</th>
            </tr>
          </thead>
        </table>
      </div>
      <div className="filesrow">
        {isLoading ? (<span id="loading">Loading...</span>) 
        : error ? (<span className="error">{error}</span>) 
        : (<div className="file-list">
            {files.length === 0 ? 
            (<span className="file-empty-dir">🈚This directory is empty.</span>) :
            (
              <table> 
                <colgroup>
                  <col className="checkbox" />
                  <col className="name" />
                  <col className="type" />
                  <col className="size" />
                </colgroup>
                <tbody>
                  {files.map((file) => (
                    <tr 
                      key={file.path} 
                      onClick={()=>handleRowClick(file)}
                      onDoubleClick={() => handleRowDoubleClick(file)}
                      className={selectedFiles.has(file.path) ? 'selected-file' : ''}
                    >
                      <td className="checkbox" 
                      onClick={(e) => e.stopPropagation()}>
                        {!file.is_dir && (
                          <input
                            type="checkbox"
                            title="select this file"
                            checked={selectedFiles.has(file.path)}
                            onChange={(e) => handleCheckboxChange(e, file.path)}
                          />
                        )}
                      </td>
                      <td className="name">{file.name}</td>
                      <td className="type">{file.is_dir ? "Directory" 
                        : file.name.includes('.') ? `${file.name.split('.').pop()}` 
                        : "File"}
                      </td>
                      <td className="size">{file.is_dir ? "--" : formatFileSize(file.size)}</td>
                    </tr>
                  ))
                  }
                </tbody>
              </table>
            )}
          </div>
          )}
      </div>
    </div>
  );
}

export default FileExplorer;
